﻿@page "/"

@namespace SageKing.Studio.Pages.PackageList

@attribute [ReuseTabsPage(Title = "消息管理中心", Closable = false, Pin = true)]

@implements IReuseTabsPage

<PageTitle>@TabTitle</PageTitle>

@inject SysMenuService _sysMenuService
@inject ISageKingPackagesService dataService

@code {

    class SendModel
    {
        [Required]
        public string Message { get; set; }

        [RequiredList]
        public IEnumerable<string> ServerIds { get; set; }
    }
}

@if (dic == null)
{
     <Spin size="SpinSize.Large" Tip="Loading..." />
}
else
{
    <Table @ref="table" TItem="KeyValue<string,List<string>>" DataSource="@dic"  Class="main-table" ScrollY="@BrowserConsts.ScrollYTable"
           @bind-SelectedRows="@selectedRows" RowKey="a=>a.Key" Size="TableSize.Small" Loading="tableLoading" Resizable Bordered EnableVirtualization PageSize="20">
        <TitleTemplate>
            <Form @ref="form"
                  Model="@model"
                  ValidateOnChange="true">
                <DataAnnotationsValidator />
                @* <ValidationSummary /> *@
                <Space>
                    <SpaceItem>
                        <Select DataSource="@serverNamelst"
                                Mode="SelectMode.Multiple"
                                Placeholder="请选择服务端"
                                @bind-Values="@model.ServerIds"
                                TItemValue="string"
                                TItem="string"
                                Style="min-width:150px; width: auto;"
                                EnableSearch
                                AllowClear>
                        </Select>
                    </SpaceItem>
                    <SpaceItem>
                        <Input @ref=inputMessageRef Placeholder="输入发送内容" @bind-Value="model.Message" AllowClear="true" ShowCount MaxLength="200" />
                    </SpaceItem>
                    <SpaceItem>
                        <Button Type="@ButtonType.Primary" @onclick="Send" Loading="@loading">发送</Button>
                    </SpaceItem>
                    <SpaceItem>
                        <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Reload" OnClick="()=>ReSet()">重置</Button>
                    </SpaceItem>
                    <SpaceItem>
                        <label class="validation-message">@Notice</label>
                    </SpaceItem>
                </Space>
            </Form>
        </TitleTemplate>

        <ColumnDefinitions>
            <Selection Key="@context.Key" Type="@selectionType"></Selection>
            <PropertyColumn Property="c=>c.Key" Title="消息类型"></PropertyColumn>
            <PropertyColumn Property="c=>c.Value.Count" Title="计数"></PropertyColumn>
            <Column TData="KeyValue<string,List<string>>" Title="内容">
                <ul>
                    @foreach (var item in context.Value)
                    {
                        <li>@item</li>
                    }
                </ul>
            </Column>
        </ColumnDefinitions>
        <PaginationTemplate>
            <Pagination ShowTotal="showTotal" Class="@(context.PaginationClass + " my-custom-pagination")"
                        Total="context.Total"
                        PageSize="context.PageSize"
                        Current="context.PageIndex"
                        ShowSizeChanger
                        ShowQuickJumper />
        </PaginationTemplate>
    </Table>
}

@code {
    bool loading;
    static bool IsfirstRender = false;

    SendModel model = new SendModel();
    AntDesign.Form<SendModel> form;

    string Notice = string.Empty;
    AntDesign.Input<string> inputMessageRef;

    //table
    ITable table;
    bool tableLoading;
     SelectionType selectionType = SelectionType.Checkbox;
    List<string> serverNamelst;
    RenderFragment<PaginationTotalContext> showTotal = ctx => @<div class="showTotal">Total: <b>@ctx.Total</b></div>;

    public string ScrollY { get; set; } = BrowserConsts.ScrollY;

    IEnumerable<KeyValue<string, List<string>>> dic;
    IEnumerable<KeyValue<string, List<string>>> selectedRows;

    #region init
    #region menu
    [SupplyParameterFromQuery(Name = "menuid")]
    public long menuid { get; set; }

    [Parameter]
    public string TabTitle { get; set; } = "消息管理中心";

    [Parameter]
    public string TabIcon { get; set; } = "home";

    public RenderFragment GetPageTitle() =>
    @<div>
        <Icon Type="@TabIcon" /> @TabTitle
    </div>
    ;
    #endregion

    [CascadingParameter]
    public Error? Error { get; set; }


    protected override async Task OnInitializedAsync()
    {
        try
        {
            await InitSelectData();

        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex, TabTitle);
        }

        // await InitTabTitle();
    }

    async Task InitSelectData()
    {
        dic = dataService.GetMessagesStringDic.Select(a => new KeyValue<string, List<string>>(a.Key, a.Value));
        serverNamelst = dataService.GetServerNames;

        await Task.CompletedTask;
    }

    #endregion
    void ReSet()
    {
        model = new SendModel();
    }
    private async void Send()
    {
        try
        {
            if (!form.Validate())
            {
                Notice = $"请选择服务器或输入消息内容";
                return;
            };

            Notice = $"开始向【{model.ServerIds.Count()}】服务端发送";

            loading = true;

            foreach (var item in model.ServerIds)
            {
                var result = await dataService.SendMsgAsync(item, model.Message.GetDataStreamBody().ToArray(), $"Test:Send");
            }

            loading = false;

            model.Message = string.Empty;
            Notice = $"完成发送【{model.ServerIds.Count()}】服务端";

            await inputMessageRef.Focus();

            StateHasChanged();
        }
        catch (Exception ex)
        {
            Error?.ProcessError(ex, TabTitle);
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            WaitTimeToRun();
        }

        if (ScrollY != BrowserConsts.ScrollYTable)
        {
            ScrollY = BrowserConsts.ScrollYTable;
            StateHasChanged();
        }

        await Task.CompletedTask;
    }

    void WaitTimeToRun()
    {
        var _this = this;
        Task.Run(() =>
        {
            while (System.Threading.SpinWait.SpinUntil(() => ScrollY != BrowserConsts.ScrollYTable, 3000))
            {
                ScrollY = BrowserConsts.ScrollYTable;
                _this.InvokeAsync(() =>
                {
                    StateHasChanged();
                });
            };

        });
    }
}
